package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"users/model/mysql"
	"users/model/redis"
	"users/pkg"

	"users/userrpc/internal/svc"
	"users/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *userrpc.UpdateRequest) (*userrpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Rdb.Get("captchaupdate" + in.Phone)
	if get.Val() != in.CaptchaCode {
		return nil, fmt.Errorf("验证码错误，请重新输入")
	}

	cmd := redis.Rdb.Get("sendSmsupdate" + in.Phone)
	if cmd.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("手机验证码错误，请重新输入")
	}
	var users mysql.User
	mysql.DB.Debug().Where("phone= ? ", in.Phone).Find(&users)
	if users.ID == 0 {
		return nil, fmt.Errorf("用户名未注册注册，请前往注册")
	}
	if users.Password != pkg.Md5Pwd(in.Password) {
		return nil, fmt.Errorf("密码错误，请重新输入")
	}
	if in.Password == in.Passwd {
		return nil, fmt.Errorf("新密码和旧密码不可以相同，请重新输入")
	}
	user := mysql.User{
		Model:    gorm.Model{ID: uint(in.Id)},
		Phone:    in.Phone,
		Password: pkg.Md5Pwd(in.Password),
	}
	mysql.DB.Debug().Updates(&user)
	redis.Rdb.Del("captchaupdate" + in.Phone)
	redis.Rdb.Del("sendSmsupdate" + in.Phone)
	return &userrpc.UpdateResponse{Id: int64(user.ID)}, nil
}
